package com.redis.redisdemo_20230217.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁
 * @author xiaojf
 */
@RestController
@RequestMapping("test2")
public class Test2Controller {

    @Autowired(required = false)
    private RedisTemplate<String, String> redisTemplate;

    private final String Lock_key1="lock1";

    private final String Lock_key2="lock2";

    @GetMapping("competeLock")
    public String competeLock(){
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(Lock_key1, "test2",10, TimeUnit.SECONDS);
        if (flag){
            return "竞争成功";
        }
        return "竞争失败";
    }

    @GetMapping("timeOut")
    public String timeOut(){
        return getLock();
    }

    public String  getLock(){
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(Lock_key2, "test2", 10, TimeUnit.SECONDS);
        if ("test2".equals(redisTemplate.opsForValue().get(Lock_key2))){
            //判断是否占锁，如果是加上失效时间

            return "当前还在占用";
        }
        return "继续等待";
    }

}
